<template>
  <view class="preview">
    <swiper circular @change="changeImg" :current="current">
      <swiper-item v-for="(item, index) in classifyList" :key="item._id">
        <image class="image" v-if="lazyImgCurrent.has(index)" :src="item.picurl" @click="onHidden" mode="aspectFill">
        </image>
      </swiper-item>
    </swiper>
    <view class="mask" v-show="!hidden">
      <view class="goBack" @click="onGoBack" :style="{ top: `${getStatusBarHeight() || 15}px` }">
        <uni-icons class="icon" type="left" size="20" color="#fff" />
      </view>
      <view class="count">{{ current + 1 }} / {{ classifyList.length }}</view>
      <view class="time">
        <uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
      </view>
      <view class="date">
        <uni-dateformat :date="Date.now()" format="MM月dd日"></uni-dateformat>
      </view>
      <view class="footer">
        <view class="box" @click="clickInfo">
          <uni-icons type="info" size="28" />
          <text class="text">信息</text>
        </view>
        <view class="box" @click="clickScore">
          <uni-icons type="star" size="28" />
          <text class="text">{{ currentInfo.score }}分</text>
        </view>
        <view class="box" @click="clickDownload">
          <uni-icons type="download" size="24" />
          <text class="text">下载</text>
        </view>
      </view>
    </view>

    <uni-popup ref="infoPopup" type="bottom"  @maskClick="clickInfoClose">
      <view class="infoPopup" :class="{fixed: fixed}">
        <view class="popHeader">
          <view></view>
          <view class="title">壁纸信息</view>
          <view class="close" @click="clickInfoClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y class="scroll">
          <view class="content">
            <view class="row">
              <view class="label">壁纸ID：</view>
              <text selectable class="value">{{ currentInfo._id }}</text>
            </view>
            <!--
    						<view class="row">
    							<view class="label">分类：</view>
    							<text class="value class">明星美女</text>
    						</view>
    						 -->
            <view class="row">
              <view class="label">发布者：</view>
              <text class="value">{{ currentInfo.nickname }}</text>
            </view>

            <view class="row">
              <text class="label">评分：</text>
              <view class='value roteBox'>
                <uni-rate readonly touchable :value="currentInfo.score" size="16" />
                <text class="score">{{ currentInfo.score }}分</text>
              </view>
            </view>

            <view class="row">
              <text class="label">摘要：</text>
              <view class='value'>
                {{ currentInfo.description }}
              </view>
            </view>

            <view class="row">
              <text class="label">标签：</text>
              <view class='value tabs'>
                <view class="tab" v-for="tab in currentInfo.tabs" :key="tab">
                  {{ tab }}
                </view>
              </view>
            </view>

            <view class="copyright">
              声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。

            </view>
            <view class="safe-area-inset-bottom"></view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <uni-popup ref="scorePopup" :is-mask-click="false">
      <view class="scorePopup">
        <view class="popHeader">
          <view></view>
          <view class="title">{{ !!currentInfo.userScore ? '&nbsp;&nbsp;已评分' : '壁纸评分' }}</view>
          <view class="close" @click="clickScoreClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>

        <view class="content">
          <uni-rate :disabled="!!currentInfo.userScore" v-model="userScore" allowHalf />
          <text class="text">{{ userScore }}分</text>
        </view>
        <view class="footer">
          <button type="default" size="mini" plain :disabled="!!currentInfo.userScore"
            @click="submitScore">确认评分</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue';
import { storeToRefs } from 'pinia'
import { getStatusBarHeight } from '@/utils/system'
import { useClassifyListStore } from '@/stores/classifyList';
import { onLoad, onShareAppMessage, onUnload } from '@dcloudio/uni-app'
import type { ClassifyWallList } from '@/api/classify';
import { apiDetailWall, apiSetupScore } from '@/api/classify';
import { uniGetImageInfo, uniSaveImageToPhotosAlbum, uniShowModal } from '@/utils/promisify';
import { apiDownloadWall } from '@/api/user';

const store = useClassifyListStore();
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { list: classifyList } = storeToRefs(store);
// 作为 action 的 increment 可以直接解构
const { setUserScore, setList } = store;

const hidden = ref(false);
// 解决原有的样式导致动画出现弹跳的问题
const fixed = ref(false);
const infoPopup = ref(null);
const scorePopup = ref(null);
const userScore = ref(0);
const current = ref(0);
const currentInfo = ref<Partial<ClassifyWallList>>({});
const lazyImgCurrent = ref<Set<number>>(new Set());

const onHidden = () => {
  hidden.value = !hidden.value;
};
const onGoBack = () => {
  uni.navigateBack({
    fail() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }
  });
};
//点击info弹窗
const clickInfo = () => {
  infoPopup.value.open();
  setTimeout(() => {
    fixed.value = true
  }, 220)
}

//点击关闭信息弹窗
const clickInfoClose = () => {
  infoPopup.value.close();
  setTimeout(() => {
    fixed.value = false
  }, 40)
}
//评分弹窗
const clickScore = () => {
  scorePopup.value.open();
}
// 关闭评分弹窗
const clickScoreClose = () => {
  scorePopup.value.close();
  if (!!currentInfo.value.userScore) {
    return
  }
  userScore.value = 0
}
// 上传评分
const submitScore = async () => {
  const { classid, _id } = currentInfo.value
  await uni.showLoading({
    mask: true
  })
  const res = await apiSetupScore({ classid, wallId: _id, userScore: String(userScore.value) })
  uni.hideLoading()
  if (res.errCode === 0) {
    uni.showToast({
      icon: 'none',
      title: '评分成功'
    })
  }
  setUserScore(_id, String(userScore.value));
  clickScoreClose()
}
onLoad(async ({ id }: { id: string }) => {
  if (!classifyList.value.length) {
    const res = await apiDetailWall({ id })
    setList(res.data)
  }

  current.value = classifyList.value.findIndex(item => item._id === id)
  currentInfo.value = classifyList.value[current.value]
  if (currentInfo.value.userScore) {
    userScore.value = Number(currentInfo.value.userScore)
  }
  setLazyImgCurrents(current.value)
})
onMounted(() => {
  console.log(infoPopup.value);
})

const changeImg = (value: any) => {
  current.value = value.detail.current
  currentInfo.value = classifyList.value[current.value]
  setLazyImgCurrents(current.value)
}

const setLazyImgCurrents = (current: number) => {
  lazyImgCurrent.value.add(current === 0 ? classifyList.value.length - 1 : current - 1)
  lazyImgCurrent.value.add(current)
  lazyImgCurrent.value.add(current === classifyList.value.length - 1 ? 0 : current + 1)
}

const clickDownload = async () => {
  // #ifdef H5
  uni.showModal({
    content: '请长按保存图片',
    showCancel: false
  })
  // #endif

  // #ifndef H5
  await uni.showLoading({
    mask: true,
    title: '下载中'
  })
  try {
    await apiDownloadWall({
      classid: currentInfo.value.classid,
      wallId: currentInfo.value._id
    })
  } catch {
    uni.hideLoading()
    return
  }
  try {
    const { path } = await uniGetImageInfo({
      src: currentInfo.value.picurl,
      complete() { uni.hideLoading() }
    })
    await uniSaveImageToPhotosAlbum({
      filePath: path
    })
  } catch ({ errMsg }) {
    // 非授权失败的场景下不做处理
    if (errMsg !== 'saveImageToPhotosAlbum:fail auth deny') {
      uni.showToast({
        title: '保存失败，请点击重新下载',
        icon: 'none'
      })
      return
    }
    const { confirm } = await uniShowModal({
      title: '提示',
      content: '需要用户授权相册权限',
    })
    // 点击确认后再执行授权操作
    if (!confirm) {
      return
    }
    const { authSetting } = await uni.openSetting()
    if (authSetting['scope.writePhotosAlbum']) {
      uni.showToast({
        title: '授权成功',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '授权失败',
        icon: 'none'
      })
    }
  }
  // #endif
}

onShareAppMessage(() => {
  return {
    title: '壁纸分享',
    path: `pages/preview/preview?id=${currentInfo.value._id}`,
  }
})
</script>

<style lang="scss" scoped>
.preview {
  position: relative;
  width: 100%;
  height: 100vh;

  swiper {
    width: 100%;
    height: 100%;

    .image {
      width: 100%;
      height: 100%;

    }
  }

  .mask {
    &>view {
      position: absolute;
      left: 0;
      right: 0;
      width: fit-content;
      margin: auto;
      color: #fff;
    }

    .goBack {
      width: 38px;
      height: 38px;
      background: rgba(0, 0, 0, 0.5);
      left: 30rpx;
      margin-left: 0;
      border-radius: 100px;
      top: 0;
      backdrop-filter: blur(10rpx);
      border: 1rpx solid rgba(255, 255, 255, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .count {
      top: 10vh;
      background-color: rgba(0, 0, 0, 0.3);
      font-size: 28rpx;
      color: #fff;
      border-radius: 40rpx;
      padding: 8rpx 28rpx;
      backdrop-filter: blur(10rpx);
    }

    .time {
      font-size: 140rpx;
      top: calc(10vh + 80rpx);
      font-weight: 100;
      line-height: 1em;
      text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
    }

    .date {
      font-size: 34rpx;
      top: calc(10vh + 210rpx);
      text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
    }

    .footer {
      background-color: rgba(255, 255, 255, 0.8);
      bottom: 10vh;
      width: 65vw;
      height: 120rpx;
      border-radius: 60rpx;
      color: #000;
      display: flex;
      justify-content: space-around;
      align-items: center;
      box-shadow: 0 2rpx rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(20rpx);

      .box {
        padding: 2rpx 12rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .text {
          font-size: 26rpx;
          color: #777;
        }
      }
    }
  }
  .infoPopup.fixed {
    // 修复弹出气泡底部样式问题，消除气泡与底部的间距，在气泡内部设置安全间距
    position: fixed;
    bottom: 0;
    left: 0;
  }
  .infoPopup {
    padding: 30rpx;
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    overflow: hidden;

    .scroll {
      max-height: 60vh;

      .content {
        .row {
          display: flex;
          padding: 16rpx 0;
          font-size: 32rpx;
          line-height: 1.7em;

          .label {
            color: var(--uni-title-3);
            width: 140rpx;
            text-align: right;
            font-size: 30rpx;
          }

          .value {
            flex: 1;
            width: 0;
          }

          .rateBox {
            display: flex;
            align-items: center;

            .score {
              font-size: 26rpx;
              color: var(--uni-title-3);
              padding-left: 10rpx;
            }
          }

          .tabs {
            display: flex;
            flex-wrap: wrap;

            .tab {
              border: 1px solid var(--uni-text-1);
              color: var(--uni-text-1);
              font-size: 22rpx;
              padding: 10rpx 30rpx;
              border-radius: 40rpx;
              line-height: 1em;
              margin: 0 10rpx 10rpx 0;
            }
          }

          .themeColor {
            color: var(--uni-text-1);
          }
        }

        .copyright {
          font-size: 28rpx;
          padding: 20rpx;
          background: #f6f6f6;
          color: #666;
          border-radius: 10rpx;
          margin: 20rpx 0;
          line-height: 1.6em;
        }
      }
    }
  }

  .popHeader {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      color: var(--uni-title-2);
      font-size: 26rpx;
    }

    .close {
      padding: 6rpx;
    }
  }

  .scorePopup {
    background: #fff;
    padding: 30rpx;
    width: 70vw;
    border-radius: 30rpx;

    .content {
      padding: 30rpx 0;
      display: flex;
      justify-content: center;
      align-items: center;

      .text {
        color: #FFCA3E;
        padding-left: 10rpx;
        width: 80rpx;
        line-height: 1em;
        text-align: right;
        font-size: 28rpx;
      }
    }

    .footer {
      padding: 10rpx 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
